from util.singelMode import singleton 
import util.chash
import modules.blockchain
import modules.db
import dto.tipblkInfo
import os
import  modules.appconfig
@singleton
class CBlockStore:
    def __init(self):
        pass
    
    def __call__(self):
        return self

    def writeBlockToDisk(self,block):
            """
            @block dto.blcock.CBlock 实例
            """
            blckNumber= int(modules.db.CDb.getValueByKey("chainIndexFile","blckNumber"))
            # storefilename=f'blk{blckNumber+1}.dat'
            storefilename=f'{block.selfhash}.dat'
            path=modules.appconfig.CAppconfig.configFromFile['chainFilePath']+block.selfhash[0:2]
            self.mkdir(path)
            filename=f'{path}/{storefilename}'
            try:
                #store the block to disk
                block.serializeToJsonfile(filename)
            except Exception:
                # if stored failed
                return None
            else:
                # if stored success
                modules.db.CDb.setValue("chainIndexFile","blckNumber",str(blckNumber+1))
                # storeInfo = f'{block.height},{block.prevBlockHash},{block.selfhash[0:2]}/{storefilename},IsNull'
                storeInfo = f'{block.height},{block.prevBlockHash},{block.txcounts},{block.timestamp}'
                modules.db.CDb.setValue("chainIndexFile",block.selfhash,storeInfo)   
                blksetByHeightstr = modules.db.CDb.getValueByKey("chainIndexFile",f'blksetByHeight{block.height}')
                if blksetByHeightstr== None:
                    modules.db.CDb.setValue("chainIndexFile",f'blksetByHeight{block.height}',f'{block.selfhash}:{block.prevBlockHash}')
                else:
                    modules.db.CDb.setValue("chainIndexFile",f'blksetByHeight{block.height}',blksetByHeightstr+f',{block.selfhash}:{block.prevBlockHash}')
                return f'{block.selfhash[0:2]}/{storefilename}'
    @staticmethod
    def mkdir(path):
        # 去除首位空格
        path=path.strip()
        # 去除尾部 \ 符号
        path=path.rstrip("\\")
    
        # 判断路径是否存在
        # 存在     True
        # 不存在   False
        isExists=os.path.exists(path)
    
        # 判断结果
        if not isExists:
            # 如果不存在则创建目录
            # 创建目录操作函数
            os.makedirs(path) 
    
            # print(path+' 创建成功')
            return True
        else:
            # 如果目录存在则不创建，并提示目录已存在
            # print(path+' 目录已存在')
            return False


                

                   
         
       

        


        
    